/**
 * 
 */
package com.fnic.pearl.scheduler.action;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.fnic.pearl.scheduler.dao.SchedulerStore;
import com.fnic.pearl.scheduler.mod.AuthManager;
import com.fnic.pearl.scheduler.mod.ProbeStatusManager;
import com.fnic.pearl.scheduler.model.ProbeLoginReq;
import com.fnic.pearl.scheduler.model.ProbeStatus;
import com.fnic.pearl.scheduler.model.SessionKey;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 探针登录
 * 
 * @author HuHaiyang
 * @date 2013年8月20日
 */
public class ProbeLoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static Logger LOG = Logger.getLogger(ProbeLoginServlet.class);

	private Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

	/**
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ProbeLoginReq loginReq = null;
		if (!AuthManager.getInstance().isLoginManager()) {
			// 如果调度器未登陆，则直接返回
			LOG.info("调度器未登陆管理节点....");
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		try {
			loginReq = gson.fromJson(new InputStreamReader(request.getInputStream()), ProbeLoginReq.class);
		} catch (Exception e) {
			LOG.error("probe login request parse exception - " + e.getMessage());
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}

		if (loginReq == null) {
			// LOG.warn("probe login request is null");
			LOG.info("请求体为空");
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		int probeId = loginReq.getProbeId();
		LOG.info("探针登录|" + probeId);
		if (probeId <= 0) {
			LOG.info("探针id<=0,probeId = " + probeId + "|" + request.getRemoteAddr());
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		} else if (probeId == 192) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		////////////////////////////////////////////////////////////////////
		ProbeStatus ps = getProbeStatus(loginReq, request);
		ProbeStatusManager.getInstance().put(ps);
		// 这句必须放在ProbeStatusManager.getInstance().put(ps);后面
		ProbeStatusManager.getInstance().updateStatus(probeId, ProbeStatus.S_LOGIN);
		// 恢复处于 hangup 状态的任务
		SchedulerStore.getInstance().switchTaskFromHangUp(probeId);
		response.setContentType("application/json;charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);
		response.getWriter().write(gson.toJson(ps.getSessionKey()));
		response.getWriter().flush();
		LOG.info("登录结束|" + ps.getProbeId());
	}

	/**
	 * 生成probe状态
	 * 
	 * @param probeId
	 * @return
	 *
	 */
	private ProbeStatus getProbeStatus(ProbeLoginReq loginReq, HttpServletRequest request) {
		int probeId = loginReq.getProbeId();
		SessionKey sessionKey = new SessionKey(probeId);
		ProbeStatus ps = ProbeStatusManager.getInstance().get(probeId);
		if (ps == null) {
			ps = new ProbeStatus();
			ps.setProbeId(probeId);
		}
		ps.setProbeName(loginReq.getProbeName());
		ps.setLastLoginIp(request.getRemoteAddr());
		ps.setLastLoginPort(request.getRemotePort());
		ps.setLastLoginTime(new Date());
		// probe version
		ps.setProbeVer(loginReq.getProbeVer());
		// mac
		if (loginReq.getMacList().size() > 0) {
			ps.setMac(loginReq.getMacList().get(0));
		}
		// icaretype
		ps.setIcareType(loginReq.getIcareType());
		// serial
		ps.setProbeSerial(loginReq.getSerial());
		ps.setLastRecvHBTime(new Date());
		ps.setSessionKey(sessionKey);
		return ps;
	}
}
